// @login & register
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const gravatar = require('gravatar');
const keys = require('../../config/keys');
const passport = require('passport');
var svgCaptcha = require('svg-captcha'); //验证码
const User = require('../../models/User');

router.get('/getCode', (req, res) => {
  var codeConfig = {
    size: 4, // 验证码长度
    ignoreChars: '0o1i', // 验证码字符中排除 0o1i
    noise: 2, // 干扰线条的数量
    fontSize: 42,
    color: true, //开启文字颜色
    background: "#cc9966", //背景色
    width: 100,
    height: 40
  }
  var captcha = svgCaptcha.create(codeConfig);

  req.session.captcha = captcha.text.toLowerCase(); //存session用于验证接口获取文字码
  // console.log(req.session)
  var codeData = {
    img: captcha.data
  }
  res.type('svg');
  res.status(200).send(captcha.data);
});



// @route  GET api/users/test
// @desc   返回的请求的json数据
// @access public
router.get('/test', (req, res) => {
  res.json({
    msg: 'login works'
  });
});

// @route  GET api/users/usersinfo
// @desc   返回的请求的json数据
// @access public

router.get('/usersinfo',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    User.find().sort({
        date: -1
      })
      .then(User => {
        if (!User) {
          return res.status(404).json('没有任何内容');
        }

        res.json(User);
      })
      .catch(err => res.status(404).json(err));
  });


// @route  POST api/users/edit
// @desc   编辑信息接口
// @access Private
router.post(
  '/edit/:id',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    const usersInfo = {};

    if (req.body.name) usersInfo.name = req.body.name;
    if (req.body.email) usersInfo.email = req.body.email;
    if (req.body.identity) usersInfo.identity = req.body.identity;

    User.findOneAndUpdate({
      _id: req.params.id
    }, {
      $set: usersInfo
    }, {
      new: true
    }).then(User => res.json(User));
  }
);

// @route  POST api/users/editavater
// @desc   编辑信息接口
// @access Private
router.post(
  '/editavater/:id',
  // passport.authenticate('jwt', {
  //   session: false
  // }),
  (req, res) => {
    const usersInfo = {};
    console.log(req.body.avatar)

    if (req.body.avatar) usersInfo.avatar = req.body.avatar;


    User.findOneAndUpdate({
      _id: req.params.id
    }, {
      $set: usersInfo
    }, {
      new: true
    }).then(User => res.json(User));
  }
);

// @route  GET api/users/usersinfo
// @desc   返回的请求的json数据
// @access public

router.get('/avatar/:id',
  // passport.authenticate('jwt', {
  //   session: false
  // }),
  (req, res) => {
    User.findOne({
        _id: req.params.id
      })
      .then(User => {
        if (!User) {
          return res.status(404).json('没有任何内容');
        }

        res.json(User.avatar);
      })
      .catch(err => res.status(404).json(err));
  });



// @route  POST api/users/delete/:id
// @desc   删除信息接口
// @access Private
router.delete(
  '/delete/:id',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    User.findOneAndRemove({
        _id: req.params.id
      })
      .then(User => {
        User.save().then(User => res.json(User));
      })
      .catch(err => res.status(404).json('删除失败!'));
  }
);


// @route  POST api/users/register
// @desc   返回的请求的json数据
// @access public
router.post('/register', (req, res) => {
  // 查询数据库中是否拥有邮箱
  User.findOne({
    email: req.body.email
  }).then(user => {
    if (user) {
      return res.status(400).json('邮箱已被注册!');
    } else {

      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        identity: req.body.identity
      });

      bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;

          newUser.password = hash;

          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });
});

// @route  POST api/users/login
// @desc   返回token jwt passport
// @access public

router.post('/login', (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  const captcha = req.body.captcha
  // console.log('/login', email, password, captcha, req.session)
  if (captcha !== req.session.captcha) {
    return res.status(400).json('验证码错误!')
  }
  // 验证通过，删除保存的验证码
  delete req.session.captcha

  // 查询数据库
  User.findOne({
    email
  }).then(user => {
    if (!user) {
      return res.status(404).json('用户不存在!');
    }

    // 密码匹配
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        const rule = {
          id: user.id,
          name: user.name,
          avatar: user.avatar,
          identity: user.identity
        };
        jwt.sign(rule, keys.secretOrKey, {
          expiresIn: 3600
        }, (err, token) => {
          if (err) throw err;
          res.json({
            success: true,
            token: 'Bearer ' + token
          });
        });
        // res.json({msg:"success"});
      } else {
        return res.status(400).json('密码错误!');
      }
    });
  });
});

// @route  GET api/users/current
// @desc   return current user
// @access Private
router.get(
  '/current',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    res.json({
      id: req.user.id,
      name: req.user.name,
      email: req.user.email,
      identity: req.user.identity
    });
  }
);




module.exports = router;